package com.atguigu.gulimall.order.listener;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.gulimall.order.config.AlipayTemplate;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.vo.PayAsyncVo;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @create: 2024/9/15
 * @author: gyhe10
 * @description: 订单支付成功监听器，接收支付宝异步通知
 * 用户支付成功后，支付宝就会不断调用商户系统配置的异步通知地址将支付结果作为参数通知到商家系统
 **/

@RestController
public class OrderPayedListener {

    @Resource
    private OrderService orderService;
    @Resource
    private AlipayTemplate alipayTemplate;

    @PostMapping("/payed/notify")
    public String handleAliPayed(PayAsyncVo vo, HttpServletRequest request) throws AlipayApiException {
        // 验签
        // 参考 https://opendocs.alipay.com/open/270/105902?pathHash=d5cd617e&ref=api 中“返回结果的验签”部分的说明
        Map<String, String> paramsMap = new HashMap<>();
        Map<String, String[]> map = request.getParameterMap();
        // 控制台打印参数
        // for (String key : map.keySet()) {
        //     System.out.println(key + ":" + request.getParameter(key));
        // }

        for (String key : map.keySet()) {
            String[] values = map.get(key);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化一下再比较，或者直接使用java.net.URLDecoder.decode("%7E", "UTF-8")
            // valueStr = new String(valueStr.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            paramsMap.put(key, valueStr);
        }
        // 调用 SDK 验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap, alipayTemplate.getAlipay_public_key(), alipayTemplate.getCharset(), alipayTemplate.getSign_type());
        if (signVerified) {
            System.out.println("验签成功");
            // 验签成功后，商户处理自身业务，比如修改订单状态、扣减库存等，最后在在 response 中返回 success
            return orderService.handlePayResult(vo);
        } else {
            // 验签失败则记录异常日志，并在 response 中返回 failure
            System.out.println("验签失败");
            return "failure";
        }
    }
}
